package com.example.microinvestmq.producer;

import com.example.microinvestcommon.entity.UserOrder;
import com.example.microinvestcommon.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderProducer {

    private final RabbitTemplate rabbitTemplate;
    private static final Logger logger = LoggerFactory.getLogger(OrderProducer.class);

    private static final String EXCHANGE_NAME = "userOrder.direct";
    private static final String BUY_ROUTING_KEY = "buyOrder.create";
    private static final String SELL_ROUTING_KEY = "sellOrder.create";

    @Autowired
    public OrderProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    //发送购买挂单
    public Result<String> buyOrderProducer(UserOrder userOrder, long ttl) {
        try {
            rabbitTemplate.convertAndSend(
                    EXCHANGE_NAME,
                    BUY_ROUTING_KEY,
                    userOrder,
                    message -> {
                        // 设置消息的 TTL（单位：毫秒）
                        message.getMessageProperties().setExpiration(String.valueOf(ttl));
                        return message;
                    }
            );

            logger.info("用户购买订单发送成功，订单ID: {}，TTL: {} ms", userOrder.getOrderId(), ttl);
            return Result.success("挂单成功");
        } catch (Exception e) {
            logger.error("订单发送失败: {}", e.getMessage());
            return Result.error("发送失败: " + e.getMessage());
        }
    }

    //   发送卖出挂单
    public Result<String> sellOrderProducer(UserOrder userOrder,long ttl) {
        try {
            rabbitTemplate.convertAndSend(
                    EXCHANGE_NAME,
                    SELL_ROUTING_KEY,
                    userOrder,
                    message -> {
                        // 设置消息的 TTL（单位：毫秒）
                        message.getMessageProperties().setExpiration(String.valueOf(ttl));
                        return message;
                    }
            );

            logger.info("用户卖出订单发送成功，订单ID: {}，TTL: {} ms", userOrder.getOrderId(), ttl);
            return Result.success("挂单成功");
        } catch (Exception e) {
            logger.error("订单发送失败: {}", e.getMessage());
            return Result.error("发送失败: " + e.getMessage());
        }
    }
}





